package com.itheima.thread.diyThread4Ways;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Ethan Yankang
 * @Program: interview
 * @Date: 2024-07-28 15:44
 **/
public class ThreadByThreadPool {
    public static void main(String[] args) {
        // 创建一个固定大小为 5 的线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        // 提交 10 个任务到线程池
        for (int i = 0; i < 10; i++) {
            executor.execute(new Task(i));
        }
        // 关闭线程池
        executor.shutdown();
    }

//    创建内部类
    static class Task implements Runnable {
        private int taskId;

        public Task(int taskId) {
            this.taskId = taskId;
        }

        @Override
        public void run() {
            System.out.println("Task " + taskId + " is running");
            try {
                // 模拟任务执行时间
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task " + taskId + " is completed");
        }
    }
}
